package com.example.mybatisplusdemo.web.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.mybatisplusdemo.model.dto.PageDTO;
import com.example.mybatisplusdemo.model.dto.ProductWithPointsDTO;
import org.springframework.web.bind.annotation.RequestMapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.example.mybatisplusdemo.common.JsonResponse;
import com.example.mybatisplusdemo.service.IProductService;
import com.example.mybatisplusdemo.model.domain.Product;


/**
 *
 *  前端控制器
 *
 *
 * @author lqj
 * @since 2025-06-24
 * @version v1.0
 */
@RestController
@RequestMapping("/api/product")
public class ProductController {

    private final Logger logger = LoggerFactory.getLogger( ProductController.class );

    @Autowired
    private IProductService productService;


    /**
    * 描述：根据Id 查询
    *
    */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse<Product> getById(@PathVariable("id") Long id)throws Exception {
        Product product = productService.getById(id);
        return JsonResponse.success(product);
    }


    @GetMapping("pageList")
    public JsonResponse selectPageList(Product product, PageDTO pageDTO)throws Exception {
        Page<Product> page = productService.pageList(product,pageDTO);
        return JsonResponse.success(page);
    }

    @PostMapping("logicDelete/{id}")
    public JsonResponse logicDelete(@PathVariable("id") Long id) {
        int result = productService.logicDeleteById(id);
        if(result > 0) {
            return JsonResponse.success("删除成功");
        } else {
            return JsonResponse.failure("删除失败，商品可能不存在或已被删除");
        }
    }

    @PostMapping("addProduct")
    public JsonResponse addProduct(@RequestBody Product product) throws Exception {
        boolean save = productService.save(product);

        // ✅ 构造 DTO，调用统一保存方法
        ProductWithPointsDTO dto = new ProductWithPointsDTO();
        dto.setProduct(product);
        dto.setPointsPrice(dto.getPointsPrice()); // ✅ 显式设置

        productService.saveProductWithPoints(dto);

        return JsonResponse.success(save);
    }


    @PutMapping("/update/{id}")
    public JsonResponse updateProduct(@PathVariable Long id, @RequestBody Product updateDto) {
        Product existing = productService.getById(id);
        if (existing == null) {
            return JsonResponse.failure("商品不存在");
        }

        // ✅ 更新字段（保留原逻辑）
        if (updateDto.getName() != null) existing.setName(updateDto.getName());
        if (updateDto.getMainImage() != null) existing.setMainImage(updateDto.getMainImage());
        if (updateDto.getProductColor() != null) existing.setProductColor(updateDto.getProductColor());
        if (updateDto.getProductSize() != null) existing.setProductSize(updateDto.getProductSize());
        if (updateDto.getInventory() != null) existing.setInventory(updateDto.getInventory());
        if (updateDto.getPrice() != null) existing.setPrice(updateDto.getPrice());
        if (updateDto.getDiscountRate() != null) existing.setDiscountRate(updateDto.getDiscountRate());
        if (updateDto.getOrigin() != null) existing.setOrigin(updateDto.getOrigin());
        if (updateDto.getBrand() != null) existing.setBrand(updateDto.getBrand());

        existing.setGroupBuy(updateDto.getGroupBuy());
        existing.setPointsMall(updateDto.getPointsMall());

        productService.updateById(existing);

        // ✅ 构造 DTO 调用统一处理逻辑
        ProductWithPointsDTO dto = new ProductWithPointsDTO();
        dto.setProduct(existing);
        dto.setPointsPrice(dto.getPointsPrice()); // ✅ 显式设置

        productService.saveProductWithPoints(dto);

        return JsonResponse.success("商品更新成功");
    }


    @PostMapping("saveProductWithPoints")
    public JsonResponse saveProductWithPoints(@RequestBody ProductWithPointsDTO dto) {
        productService.saveProductWithPoints(dto);
        return JsonResponse.success("保存成功");
    }

    @GetMapping("getPointsPriceByProductId/{id}")
    public JsonResponse<ProductWithPointsDTO> getPointsPriceByProductId(@PathVariable("id") Long id) throws Exception {
        ProductWithPointsDTO dto = productService.getPointsPriceByProductId(id);
        return JsonResponse.success(dto);
    }

    @GetMapping("/pageListWithSort")
    public JsonResponse selectPageListWithSort(
            Product product,
            PageDTO pageDTO,
            @RequestParam(required = false) String orderBy,
            @RequestParam(required = false) String sort
    ) {
        Page<Product> page = productService.pageListWithSort(product, pageDTO, orderBy, sort);
        return JsonResponse.success(page);
    }


}

